import React, { useEffect, useState } from "react";
import "../../scss/hwb_css/increased.scss"
import { questionAPI, stageAPI, questionAPI_del,questionAPI_status } from "./hwb_API.jsx";
import { Select, Button, Table, Flex, Modal } from "antd";
import { useSearchParams, useNavigate } from "react-router-dom";
import { Pagination } from "tdesign-react";
import moment from "moment";

function Increased() {
  let navigate = useNavigate();
  let [select, setSelect] = useSearchParams();
  let [question_list, setQuestion_list] = useState([]);
  let [stage_list, setStage_list] = useState([]);

  //分页
  const [page, setPage] = useState(1);
  const [pagesize, setPagesize] = useState(2);
  const [total, setTotal] = useState(0);

  const onChange = React.useCallback((pageInfo) => {
    const index = pageInfo.current;
    setPage(index);
  }, []);
  const onPageSizeChange = React.useCallback((index, pageInfo) => {
    setPagesize(index);
  }, []);

  //试题表
  const getQuestion = async () => {
    let id = select.get("id");
    let {
      data: { question_list, total },
    } = await questionAPI({ cate, difficulty, page, pagesize, id });
    setQuestion_list(question_list);
    setTotal(total);
  };

  //试题分类表
  const getSage = async () => {
    let {
      data: { stage_list },
    } = await stageAPI();
    setStage_list(stage_list);
  };
  //搜索
  const search = () => {
    getQuestion();
  };
  //重置
  const reset = () => {
    setCate(0);
    setDifficulty(0);
    getQuestion();
    getSage();
  };
  //搜索stage
  //题型
  const [cate, setCate] = useState(0);
  const onChange2 = (value) => {
    setCate(value);
  };
  //难度
  const [difficulty, setDifficulty] = useState(0);
  const onChange3 = (value) => {
    setDifficulty(value);
  };

  //渲染
  const [columns, setColumns] = useState([
    {
      title: "试题分类",
      dataIndex: "belong",
    },
    {
      title: "题型分类",
      dataIndex: "cate",
    },
    {
      title: "题干",
      dataIndex: "title",
    },
    {
      title: "正确选项",
      dataIndex: "options",
    },
    {
      title: "难度",
      dataIndex: "difficulty",
    },
    {
      title: "创建日期",
      dataIndex: "timing",
    },
    {
      title:"审核状态",
      dataIndex: "status",
    },
    {
      title: "操作",
      dataIndex: "caozuo",
    },
  ]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pldel_list, setPldel_list] = useState([]);
  const start = () => {
    setLoading(true);
    // ajax request after empty completing
    setTimeout(() => {
      setSelectedRowKeys([]);
      setLoading(false);
    }, 1000);
  };
  const onSelectChange = (newSelectedRowKeys) => {
    // console.log("selectedRowKeys changed: ", newSelectedRowKeys)//批量删除获取ID
    setSelectedRowKeys(newSelectedRowKeys);
    setPldel_list(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const hasSelected = selectedRowKeys.length > 0;

  //批量删除
  const pldel = async () => {
    let ids = pldel_list;
    Modal.confirm({
      title: "提示",
      content: "确定要删除吗？",
      onOk: async () => {
        await questionAPI_del({ ids });
        getQuestion();
        getSage();
      },
    });
  };
  //删除
  const del = async (id) => {
    Modal.confirm({
      title: "提示",
      content: "确定要删除吗？",
      onOk: async () => {
        await questionAPI_del({ ids: [id] });
        getQuestion();
        getSage();
      },
    });
  };

  // 修改状态
  const ups=async(id,status)=>{
    await questionAPI_status({id,status});
    getQuestion();
    getSage();
  }

  useEffect(() => {
    getQuestion();
    getSage();
  }, [page, pagesize]);

  return (
    <div>
      <div className="increased">
        <div className="header">
          <p className="p1">
            {stage_list
              .filter((ele) => ele._id === select.get("id"))
              .map((item) => (
                <span key={item._id}>{item.name}</span>
              ))}
          </p>
          <div className="head1">
            <div className="nav2">
              <span>题型：</span>
              <Select
                showSearch
                placeholder="请选择"
                optionFilterProp="label"
                onChange={onChange2}
                value={cate ? cate : "请选择"}
                options={[
                  {
                    value: "1",
                    label: "单选题",
                  },
                  {
                    value: "2",
                    label: "多选题",
                  },
                  {
                    value: "3",
                    label: "判断题",
                  },
                  {
                    value: "4",
                    label: "简答题",
                  },
                ]}
                style={{ width: "12.5rem" }}
              />
            </div>
            <div className="nav3">
              <span>难度：</span>
              <Select
                showSearch
                placeholder="请选择"
                optionFilterProp="label"
                onChange={onChange3}
                value={difficulty ? difficulty : "请选择"}
                options={[
                  {
                    value: "1",
                    label: "简单",
                  },
                  {
                    value: "2",
                    label: "一般",
                  },
                  {
                    value: "3",
                    label: "困难",
                  },
                ]}
                style={{ width: "12.5rem" }}
              />
            </div>
            <div className="nav4">
              <Button type="primary" onClick={search}>
                查询
              </Button>
              <Button onClick={reset}>重置</Button>
            </div>
          </div>
          <div className="head2">
            <Button
              type="primary"
              onClick={() => {
                navigate("/home/topic");
              }}
            >
              新增试题
            </Button>
            <Button onClick={pldel}>批量删除</Button>
          </div>
        </div>
        <div className="content">
          <Flex gap="middle" vertical>
            <Flex align="center" gap="middle">
              <Button
                type="primary"
                onClick={start}
                disabled={!hasSelected}
                loading={loading}
              >
                Reload
              </Button>
              {hasSelected ? `Selected ${selectedRowKeys.length} items` : null}
            </Flex>

            <Table
              rowSelection={rowSelection}
              columns={columns}
              dataSource={question_list.map((item) => ({
                key: item._id,
                belong: (
                  <p>
                    {/* {stage_list.map((item2) => {
                        if (item2._id === item.belong) {
                          return item2.name;
                        }
                      })} */}
                    {item.belong.name}
                  </p>
                ),
                cate: (
                  <p>
                    {item.cate === 1
                      ? "单选题"
                      : item.cate === 2
                      ? "多选题"
                      : item.cate === 3
                      ? "判断题"
                      : "简答题"}
                  </p>
                ),
                title: item.title,
                options: item.options.map((item) => {
                  if (item.isRight) {
                    return <span key={item._id}>{item.title.charAt(0)}</span>;
                  }
                }),
                difficulty: (
                  <p>
                    {item.difficulty === 1
                      ? "简单"
                      : item.difficulty === 2
                      ? "一般"
                      : "困难"}
                  </p>
                ),
                timing: moment(item.timing).format("YYYY-MM-DD HH:mm:ss"),
                status:item.status === 1 ? "审核通过" : "不通过",
                caozuo: (
                  <div>
                    {item.status === 1?<Button
                      type="primary"
                      size="middle"
                      onClick={() => {
                        ups(item._id,item.status)
                      }}
                    >
                      撤回
                    </Button>:<Button
                      type="primary"
                      size="middle"
                      onClick={() => {
                        ups(item._id,item.status)
                      }}
                    >
                      通过
                    </Button>}
                    <Button
                      type="primary"
                      size="middle"
                      onClick={() => {
                        navigate("/home/topic", { state: { item: item } });
                      }}
                    >
                      编辑
                    </Button>
                    <Button
                      type="primary"
                      size="middle"
                      onClick={() => {
                        del(item._id);
                      }}
                    >
                      删除
                    </Button>

                    
                  </div>
                ),
              }))}
              pagination={false}
            />
          </Flex>
        </div>
        <div className="foot">
          <Pagination
            showJumper
            total={total}
            current={page}
            pageSize={pagesize}
            onChange={onChange}
            onPageSizeChange={onPageSizeChange}
            pageSizeOptions={[1, 2, 3, 4, 5, 6, 7]}
          />
        </div>
      </div>
    </div>
  );
}

export default Increased;
